﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Lails.MQClient.PerformanceTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输入：1表示做为发布端，2表示订阅端，3退出");
            string type = Console.ReadLine();
            switch (type)
            {
                case "1":
                    Publish();
                    break;
                case "2":
                    Subscribe();
                    break;
                case "3":
                    break;
                default:
                    break;
            }

            Console.WriteLine("按任意键退出");
            Console.ReadKey();
        }

        static void Publish()
        {
            Console.WriteLine("请输入要发送的数量：");
            int count = Convert.ToInt32(Console.ReadLine());
            MQClient client = CreateClient("publisher");
            client.Connect();
            Stopwatch timer = new Stopwatch();
            timer.Start();
            int thread = 2, complete = 0;
            for (int t = 0; t < thread; t++)
            {
                ThreadPool.QueueUserWorkItem(work =>
                {
                    for (int i = 0; i < count / t; i++)
                    {
                        string message = $"This is a Rabbitmq Message:{i}, Data = ###########################################################################";
                        byte[] body = Encoding.UTF8.GetBytes(message);
                        client.Publish("msg", body);
                        //Console.WriteLine($"发送消息：{message}");
                    }
                    if (++complete == thread)
                    {
                        timer.Stop();
                        Console.WriteLine($"总共发布{count}条，耗时{timer.ElapsedMilliseconds}毫秒，平均速率{ count / timer.ElapsedMilliseconds * 1000 }条/秒。");
                    }
                });
            }
        }

        static int count = 0;
        static void Subscribe()
        {
            MQClient client = CreateClient("consumer");
            client.Connect();
            client.Subscribe("msg", OnSubscibe);
        }

        static bool OnSubscibe(byte[] data)
        {
            Console.WriteLine($"接收消息{++count}条");
            return true; //ACK
        }

        static MQClient CreateClient(string clientID)
        {
            MQClient client = new RabbitMQClient("rabbitmq.lails.cc", "demo", "demo", clientID, appid: "demo");
            return client;
        }
    }
}
